<template>
    <view class="content">
        <view class="main">
            <view class="box">
                <view class="predetermine">
                    <view class="tit">预订信息</view>
                    <view class="store df-c">
                        <image src="/static/order-md.png" />
                        <view>{{ mainStoreInfo.shopName }}</view>
                    </view>
                    <view class="desk-no df-c">
                        <image src="/static/order-tq.png" />
                        <view>{{ orderInfo.billiardMainName }}</view>
                    </view>
                    <view class="time df-c">
                        <image src="/static/order-time.png" />
                        <view>{{ orderInfo.startTime }}-{{ orderInfo.endTime }}</view>
                    </view>
                </view>
                <view class="total-price">
                    <view class="price-tit">
                        <view>总价</view>
                        <view>{{ orderInfo.price / 100 }}元</view>
                    </view>
                    <view class="times">
                        <view class="times">
                            <view class="item" v-for="item in payPriceObj.itemGroupList" :key="item.skuId">
                                <!-- <view>{{ beginAenEndTime }}</view> -->
                                <view style="flex: 1">{{ item.orderItemStartTime }}--{{ item.orderItemEndTime }}</view>
                                <view style="flex: 1">{{ ((item.price * 2) / 100).toFixed(0) }} 元/小时</view>
                                <view style="width: 120rpx; text-align: right">{{ (item.subItemPrice / 100).toFixed(2) }}元</view>
                            </view>
                            <!-- <view class="discount" style="text-align:right" v-if="payPriceObj.totalPrice !== payPriceObj.payPrice">-{{((payPriceObj.totalPrice - payPriceObj.payPrice) / 100).toFixed(2)}}元</view> -->
                        </view>
                    </view>
                    <view class="coupon" @click="goCoupon" v-if="!groupCouponId && payPriceObj.items?.length">
                        <view style="flex: 1">优惠券</view>
                        <view class="coupon-r">
                            <view class="coupon-num" v-if="!groupBuyCouponId">{{ couponNum || 0 }}张可用</view>
                            <view class="coupon-num" v-else>-{{ ((payPriceObj.totalPrice - payPriceObj.payPrice) / 100).toFixed(2) }}元</view>
                            <image class="jt" src="/static/jt.png" />
                        </view>
                    </view>
                </view>
                <view class="box pay-type" v-if="!groupCouponId">
                    <view class="tit">支付方式</view>
                    <view class="type-list">
                        <view class="item" v-for="(item, index) in payType" :key="index" @click="selectPayType(item)">
                            <view class="item-l">
                                <image class="icon" :src="item.icon" />
                                <view>
                                    <view>
                                        {{ item.label }}
                                        <text v-if="item.value === 1"
                                            >(¥{{ myWallet.balance / 100 }})</text
                                        >
                                    </view>
                                    <view @click.stop="goRecharge" class="desc" v-if="item.value === 1 && noMoney">
                                        <text>余额不足，充值享优惠</text>
                                        <image class="jiantou" src="/static/jt.png" />
                                    </view>
                                </view>
                            </view>
                            <view class="item-r">
                                <view>
                                    <image src="/static/select-disabled.png" v-if="item.disable" />
                                    <view v-else>
                                        <image src="/static/yhj-check.png" v-if="item.value === checkPayType" />
                                     <image src="/static/yhj-nocheck.png" v-if="item.value !== checkPayType" />
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="notice">
                    <view class="tit">预订须知</view>
                    <view>预订成功后全时段保留球台。</view>
                    <view>预订时间开始时系统将自动为您亮灯开台。</view>
                </view>
                <view class="refund">
                    <view class="tit">预订须知</view>
                    <view>预订成功后，平台暂不支持修改订单。</view>
                    <view>
                        <text class="time">开台一小时</text>
                        <text>前支持随时申请全额退款，逾期不可退款。</text>
                    </view>
                </view>
            </view>
        </view>
        <view class="footer" @click="creatSubmit">
            <view class="btn">
                <view class="btn-l">
                    <view class="tatol-price">合计：¥{{ orderInfo.price / 100 }}</view>
                    <!-- <view class="discount">已优惠：¥50.00</view> -->
                </view>
                <view class="btn-r">
                    <view>{{groupCouponId ? "团购券支付" : payTypeCheck.label}}</view>
                    <image class="jt" src="/static/jt-b.png" />
                </view>
            </view>
        </view>
    </view>
</template>
<script setup>
import { ref, reactive, watch, getCurrentInstance, onMounted } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { listItemByMainId, billiardSettlement, orderSubmit, createBilliardOrder, getBilliardMatchCouponList,getWallet } from "@/service/index";
const orderInfo = ref({});
const billiardOrderInfo = ref({});
const payPriceObj = ref({});
const mainStoreInfo = ref({});
const couponNum = ref(0);
const groupCouponId = ref(0);
const groupBuyCouponId = ref(null);
const groupBuyCoupon = ref({});
const noMoney = ref(false);
const checkPayType = ref(2);
const payTypeCheck = ref({label: "微信支付",});
const myWallet = ref({ balance: 0 });
const payType = ref([
    {
        value: 1,
        label: "余额支付",
        icon: "/static/wx-pay-2.png",
        disable: false,
    },
    {
        value: 2,
        label: "微信支付",
        icon: "/static/wx-pay-1.png",
        disable: false,
    },
]);
const selectPayType = (item) => {
    if(item.disable) return;
//   if (noMoney.value) {
//     return;
//   }
//   if(groupBuyCoupon.value?.payWay?.includes('wx_lite')){
//     return;
//   }
//   if(groupBuyCoupon.value?.payWay?.includes('wallet')){
//     return;
//   }
  payTypeCheck.value = item;
  checkPayType.value = item.value
};
const getMyWallet = () => {
  getWallet({isLogin:false}).then((res) => {
    myWallet.value = res;
    if(!myWallet.value.balance){
        payType.value[0].disable = true;
        uni.hideLoading();
    }
  });
};
const getPayMount = () => {
    const params = { ...billiardOrderInfo.value, couponId: groupBuyCouponId.value };
    uni.showLoading({
        mask: true,
    });

    billiardSettlement(params)
        .then(res => {
            getNewCouponList({ ...params, items: res.items });
            payPriceObj.value.payPrice = res.price.payPrice;
            payPriceObj.value.totalPrice = res.price.totalPrice;
            payPriceObj.value.items = res.items;
            payPriceObj.value.itemGroupList = res.itemGroupList;
            orderInfo.value.price = res.price.payPrice;
            if (!groupCouponId.value) {
                // 只能使用优惠卷支付
                if(groupBuyCoupon.value.payWay?.includes('wx_lite')){
                return;
                }
                if (payPriceObj.value.payPrice > myWallet.value.balance) {
                payTypeCheck.value = payType.value[1];
                noMoney.value = true;
                } else {
                payTypeCheck.value = payType.value[0];
                noMoney.value = false;
                }
            }
            uni.hideLoading();
        })
        .catch(err => {
            uni.hideLoading();
            uni.showModal({
                title: err.msg || "请求数据出错",
                showCancel: false,
            });
        });
};
// 新获取订单可用优惠卷数据
const getNewCouponList = data => {
    const params = {
        ...data,
    };
    getBilliardMatchCouponList(params).then(res => {
        couponNum.value = res?.filter(v => v.matchFlag === 1).length || 0;
        uni.setStorageSync("orderUserCouponList", res);
         uni.hideLoading();
    });
};
const creatSubmit = () => {
    const params = { ...orderInfo.value, couponId: groupBuyCouponId.value || groupCouponId.value || '' };
      if (payTypeCheck.value.value == 1) {
        params.channelCode = "wallet";
      }
    uni.showLoading({
        mask: true,
    });
    createBilliardOrder(params)
        .then(res => {
            payOrder(res);
        })
        .catch(() => {
            uni.hideLoading();
        });
};
const goCoupon = () => {
    uni.navigateTo({
        url: `/pages/coupon/orderCoupon`,
    });
};
const payOrder = param => {
    console.log(param, "param");
    const orderid = param.id;
    const params = {
        id: param.payOrderId,
        channelCode: "wx_lite",
        channelExtras: {
            openid: uni.getStorageSync("openid"),
        },
        // orderDuration:Math.abs(orderDuration.value)
    };
      if (payTypeCheck.value.value == 1) {
        params.channelCode = "wallet";
      }
    orderSubmit(params)
        .then(res => {
            const payConfig = JSON.parse(res.displayContent);
            console.log(payConfig, "pay");
              if (payTypeCheck.value.value == 1) {
                uni.showToast({
                  title: "支付成功",
                  icon: "none",
                });
                uni.redirectTo({
                  url: `/pages/order/detail?id=${orderid}`,
                });
                return;
              }
            uni.requestPayment({
                provider: "wxpay",
                timeStamp: payConfig.timeStamp,
                nonceStr: payConfig.nonceStr,
                package: payConfig.packageValue,
                signType: payConfig.signType,
                paySign: payConfig.paySign,
                success: res => {
                    console.log(orderid, "orderid");
                    uni.redirectTo({
                        url: `/pages/order/detail?id=${orderid}`,
                    });
                    uni.hideLoading();
                },
                fail: err => {
                    uni.hideLoading();
                    if (err.errMsg === "requestPayment:fail cancel") {
                        uni.showToast({
                            title: "支付已取消",
                            icon: "none",
                        });
                    } else {
                        console.log(err, "err");
                    }
                },
            });
        })
        .catch(err => {
            if (err.code === 1007002002) {
                uni.redirectTo({
                    url: `/pages/order/detail?id=${orderid}`,
                });
            }
            uni.hideLoading();
        });
};
// 选择优惠劵
const isCheckCounp = () => {};
const goRecharge = () => {
    uni.navigateTo({
        url: "/pages/recharge/index",
    });
};
onLoad((options) => {
    orderInfo.value = uni.getStorageSync("creatOrderData");
    billiardOrderInfo.value = uni.getStorageSync("billiardOrderInfo");
    mainStoreInfo.value = uni.getStorageSync("mainStoreInfo");
    if(options.couponId){
        groupCouponId.value = options.couponId;
    }
});
onShow(() => {
    const couponData = uni.getStorageSync("couponData");
    console.log(couponData, "couponData");
    getMyWallet();
    if (couponData) {
        // 选择了优惠卷
        groupBuyCoupon.value = couponData;
        groupBuyCouponId.value = couponData.id;
           if(groupBuyCoupon.value.payWay?.includes('wx_lite')){
                payTypeCheck.value = payType.value[1];
                payType.value[0].disable = true;
                checkPayType.value = 2
                console.log(payTypeCheck.value);
            }
            if(groupBuyCoupon.value.payWay?.includes('wallet')){
                payType.value[1].disable = true;
                checkPayType.value = 1
                payTypeCheck.value = {
                        value: 1,
                        label: "仅限余额支付",
                        icon: "/static/wx-pay-2.png",
                        disable: false,
                    };
                            }
    }
    getPayMount();
});
</script>
<style lang='less' scoped>
.content {
    display: flex;
    flex-direction: column;
    height: 100vh;

    // padding: 24rpx;
    .df-c {
        display: flex;
        align-items: center;
    }

    .main {
        background-color: #f7f7f7;
        padding: 24rpx;
        flex: 1;
        overflow-y: auto;

        .predetermine {
            padding: 30rpx 26rpx;
            border-bottom: 2rpx solid #eeeeee;
            background-color: #fff;

            .tit {
                margin-bottom: 24rpx;
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #333333;
            }

            .store {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #333333;
                margin-bottom: 24rpx;
            }

            .desk-no {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                color: #333333;
                margin-bottom: 24rpx;
            }

            .time {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                color: #333333;
            }

            image {
                width: 36rpx;
                height: 36rpx;
                margin-right: 16rpx;
            }
        }

        .total-price {
            padding: 30rpx 26rpx;
            border-bottom: 2rpx solid #eeeeee;

            .price-tit {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 10rpx;
            }

            .times {
                font-size: 26rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                color: #666666;
                margin-bottom: 20rpx;

                .item {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 10rpx;
                }
            }

            .coupon {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .jt {
                    width: 18rpx;
                    height: 32rpx;
                    margin-left: 16rpx;
                }

                .coupon-r {
                    display: flex;
                    align-items: center;
                }

                .coupon-num {
                    color: #ff5d15;
                }
            }
        }
        .pay-type {
            padding: 20rpx 20rpx;
            background-color: #fff;
            .tit {
                font-weight: 600;
                font-size: 28rpx;
                color: #000000;
                margin-bottom: 22rpx;
            }
            .type-list {
                .item {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 32rpx;
                    .item-l,
                    .item-r {
                        display: flex;
                        align-items: center;
                        .desc {
                            display: flex;
                            align-items: center;
                            font-size: 24rpx;
                            color: #ff5d15;
                            .jiantou {
                                width: 12rpx;
                                height: 21rpx;
                                margin-left: 10rpx;
                            }
                        }
                    }
                    .item-r {
                        image {
                            width: 36rpx;
                            height: 36rpx;
                        }
                    }
                    .icon {
                        width: 72rpx;
                        height: 72rpx;
                        margin-right: 20rpx;
                    }
                }
            }
        }
        .notice {
            font-weight: 400;
            color: #666666;
            padding: 30rpx 26rpx;
            border-bottom: 2rpx solid #eeeeee;

            view {
                line-height: 48rpx;
            }

            .tit {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                margin-bottom: 10rpx;
            }
        }

        .refund {
            font-weight: 400;
            color: #666666;
            padding: 30rpx 26rpx;

            view {
                line-height: 48rpx;
            }

            .tit {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                margin-bottom: 10rpx;
            }

            .time {
                color: #ff5d15;
            }
        }
    }

    .footer {
        padding: 34rpx 26rpx;
        box-shadow: 0rpx -12rpx 40rpx 0rpx rgba(0, 0, 0, 0.06);
        background-color: #fff;

        .btn {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            background: linear-gradient(315deg, #00b952 0%, #00e565 100%);
            border-radius: 60rpx;
            height: 120rpx;
            padding: 18rpx 42rpx;
            box-sizing: border-box;
            &::after {
                content: "";
                position: absolute;
                left: 60%;
                height: 100%;
                background-color: rgba(255, 255, 255, 0.3);
                width: 2rpx;
            }
            .btn-l {
                .tatol-price {
                    font-size: 32rpx;
                    font-weight: 600;
                    color: #ffffff;
                    line-height: 44rpx;
                }

                .discount {
                    font-size: 24rpx;
                    font-weight: 400;
                    color: #ffffff;
                }
            }

            .btn-r {
                display: flex;
                align-items: center;
                color: #fff;
                position: relative;
                .jt {
                    margin-left: 24rpx;
                    width: 18rpx;
                    height: 32rpx;
                }
            }
        }
    }
}
</style>